<template>
  <div>
    <YaPageContent
      ref="multipleTableRef"
      :formData="serchformData"
      :formColumns="serchColumns"
      :tableData="tableData"
      :tableColumns="column"
      :leftButtons="leftButtons"
      searchLabelWidth="90px"
      @search="initData('init')"
      @reset="reset"
      @tableBtnClick="tableBtnClick"
      @selectionChange="handleSelectionChange"
      :currentPage="serchformData.pageIndex"
      :pageSize="serchformData.pageSize"
      :total="total"
      @sizeChange="sizeChange"
      @currentChange="currentChange"
      @sortChange="handleSortChange"
    >
      <template v-slot:ipv4="{ item }">
        <div class="ya-ipv" @click="goToApplication(item)">
          {{ item.ipv4 || "-" }}
        </div>
      </template>
      <template v-slot:ipv6="{ item }">
        <div class="ya-ipv" @click="goToApplication(item)">
          {{ item.ipv6 || "-" }}
        </div>
      </template>
      <template v-slot:state="{ item }">
        <div v-if="item.assetStatus == 'survive'" class="ya-status">
          <img src="../../../assets/imgs/cunhuo.png" alt="" class="ya-img" />
          <span class="ya-alive">存活</span>
        </div>
        <div v-else-if="item.assetStatus == 'offLine'" class="ya-status">
          <img src="../../../assets/imgs/lixian.png" alt="" class="ya-img" />
          <span class="ya-offline">离线</span>
        </div>
        <div v-else-if="item.assetStatus == 'abnormal'" class="ya-status">
          <img src="../../../assets/imgs/yichang.png" alt="" class="ya-img" />
          <span class="ya-abnormal">异常</span>
        </div>
        <div v-else>-</div>
      </template>
      <template v-slot:level="{ item }">
        <div v-if="item.riskLevel == 'low'" class="ya-status">
          <img src="../../../assets/imgs/diwei.png" alt="" class="ya-img" />
          <span>低危</span>
        </div>
        <div v-else-if="item.riskLevel == 'middle'" class="ya-status">
          <img src="../../../assets/imgs/middle.png" alt="" class="ya-img" />
          <span>中危</span>
        </div>
        <div v-else-if="item.riskLevel == 'high'" class="ya-status">
          <img src="../../../assets/imgs/gaowei.png" alt="" class="ya-img" />
          <span>高危</span>
        </div>
        <div v-else-if="item.riskLevel == 'safe'" class="ya-status">
          <img src="../../../assets/imgs/ssafe.png" alt="" class="ya-img" />
          <span>安全</span>
        </div>
        <div v-else-if="item.riskLevel == 'unknown'" class="ya-status">
          <img src="../../../assets/imgs/sunknow.png" alt="" class="ya-img" />
          <span>未知</span>
        </div>
        <div v-else>-</div>
      </template>
      <!-- <template v-slot:tag="{ item }">
        <yaTooltip
          placement="top"
          :enterable="false"
          :hide-after="0"
          :content="
            item.assetTagNameSet && item.assetTagNameSet.length > 0
              ? item.assetTagNameSet.toString()
              : '-'
          "
        >
          <div
            class="ya-tag"
            v-if="item.assetTagNameSet && item.assetTagNameSet.length > 0"
          >
            <div class="ya-tag1" v-if="item.assetTagNameSet[0]">
              {{ item.assetTagNameSet[0] }}
            </div>
            <div class="ya-tag2" v-if="item.assetTagNameSet[1]">
              {{ item.assetTagNameSet[1] }}
            </div>
            <div class="ya-tag3" v-if="item.assetTagNameSet[2]">
              {{ item.assetTagNameSet[2] }}
            </div>
            <div class="ya-num" v-if="item.assetTagNameSet.length - 3 > 0">
              + {{ item.assetTagNameSet.length - 3 }}
            </div>
          </div>
          <div v-else>-</div>
        </yaTooltip>
      </template> -->
      <template v-slot:done="{ item }">
        <span v-if="bottomData.has(20005)" @click="goToDetail(item)">
          <TableBtns :title="bottomData.get(20005).label" type="8"></TableBtns>
        </span>
      </template>
    </YaPageContent>
    <ya-dialog
      v-if="dialogProps.showDialog"
      :dialogProps="dialogProps"
      @open="handleDialogOpen()"
      title="选择格式"
    >
      <template #content>
        <ya-form
          @handleEvent="handleDialogEvent"
          :formColumns="formColumns"
          labelWidth="100px"
          :formData="formData"
          :rules="rules"
          :ref="
            (el) => {
              if (el) dialogForm = el;
            }
          "
        >
        </ya-form>
      </template>
      <template #footer>
        <ya-button @click="dialogProps.showDialog = false">取消</ya-button>
        <ya-button type="primary" @click="handleConfirm">确定</ya-button>
      </template>
    </ya-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from "vue";
import { usePermissions } from "../../../composables/usePermissions";
import { useRouter } from "vue-router";
import { getDictList, downLoadFile } from "../../../utils/utils";
import { yaMessage } from "../../../utils/message";
import {
  queryHostAssets,
  batchExp,
  addDataExp,
} from "../../../api/digitalAssets/networkAssets/hostAssets";
import { ElTable } from "element-plus";
import { getDeptData } from "../../../api/digitalAssets/networkAssets/hostAssets";
const router = useRouter();
const { permissionsButtons } = usePermissions();
//资产类型
const assetTypeArr = ref([]);
//资产状态
const assetStatusArr = ref([]);
//风险等级
// const riskLevelArr = ref([]);
//弹框的文件类型
const fileTypeArr = ref([]);
//网络域
const networkAreaArr = ref([]);
//所属部门
const deptIdArr = ref([]);
//字典
const initDict = async () => {
  fileTypeArr.value = (await getDictList("excelType")) as [];
  // riskLevelArr.value = (await getDictList("riskLevel")) as [];
  networkAreaArr.value = (await getDictList("networkArea")) as [];
  assetTypeArr.value = (await getDictList("assetType")) as [];
  assetStatusArr.value = (await getDictList("assetStatus")) as [];
};

//搜索区域的内容
const serchColumns = reactive([
  {
    key: "target",
    type: "text",
    label: "资产IP",
  },
  // {
  //   key: "domain",
  //   type: "text",
  //   label: "域名",
  // },
  // {
  //   key: "port",
  //   type: "text",
  //   label: "端口",
  //   isType: "number",
  // },
  {
    key: "name",
    type: "text",
    label: "资产名称",
  },
  {
    key: "networkAreaCodeSet",
    type: "select",
    label: "网络域",
    options: networkAreaArr,
  },
  {
    key: "assetTypeSet",
    type: "select",
    label: "资产类型",
    options: assetTypeArr,
    multiple: true,
    collapseTags: true,
    clearable: true,
  },
  {
    key: "assetStatusSet",
    type: "select",
    label: "资产状态",
    options: assetStatusArr,
  },
  // {
  //   key: "riskLevelSet",
  //   type: "select",
  //   label: "风险等级",
  //   options: riskLevelArr,
  // },
  {
    key: "deptIdSet",
    type: "select",
    multiple: true,
    label: "所属部门",
    options: deptIdArr,
    collapseTags: true,
    clearable: true,
  },
  {
    key: "findTime",
    type: "daterange",
    label: "更新时间",
    valueFormat: "YYYY-MM-DD",
    placeholder: "选择日期",
    startPlaceholder: "开始时间",
    endPlaceholder: "结束时间",
  },
]);

// 搜索筛选出的条件 demo
const serchformData = ref({
  pageIndex: 1,
  column: "",
  asc: null,
});

//列表区域的表头
const column: any[] = reactive([
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "ipv4",
    label: "IPv4",
    slotName: "ipv4",
    minWidth: "150px",
    sortable: "custom",
  },
  {
    prop: "ipv6",
    label: "IPv6",
    slotName: "ipv6",
    minWidth: "150px",
  },

  // {
  //   prop: "domain",
  //   label: "域名",
  //   minWidth: "160px",
  // },
  {
    prop: "name",
    label: "资产名称",
    minWidth: "200px",
  },
  {
    prop: "networkAreaName",
    label: "网络域",
    minWidth: "120px",
  },
  {
    prop: "assetTypeName",
    label: "资产类型",
    minWidth: "140px",
  },
  // {
  //   prop: "os",
  //   label: "操作系统",
  //   width: "120px",
  // },
  // {
  //   prop: "gatherType",
  //   label: "采集方式",
  //   minWidth: "120px",
  // },
  {
    prop: "assetStatus",
    label: "资产状态",
    slotName: "state",
    width: "110px",
  },
  // {
  //   prop: "riskLevel",
  //   label: "风险等级",
  //   slotName: "level",
  //   width: "110px",
  // },
  // {
  //   prop: "assetTagNameSet",
  //   label: "资产标签",
  //   slotName: "tag",
  //   minWidth: "280px",
  // },
  {
    prop: "deptName",
    label: "所属部门",
    minWidth: "130px",
  },
  {
    prop: "gmtModified",
    label: "更新时间",
    width: "190px",
  },
  {
    slotName: "done",
    label: "操作",
    width: "90px",
    fixed: "right",
  },
]);

// 从后端获取来的列表区域的内容
let tableData = ref([]);

//点击多选框选中的行的数据
let selectData = ref([]);
//按钮的数据
let bottomData: any = new Map();

//左边按钮
let leftButtons: any = ref([]);

// 获取列表数据 (根据搜索条件重新渲染列表)
const initData = (data?) => {
  if (data == "init") {
    serchformData.value.pageIndex = 1;
  }
  // 保存筛选条件
  if (data) {
    sessionStorage.setItem("YA_FORM_DATA", JSON.stringify(serchformData.value));
  }
  if (sessionStorage.getItem("YA_FORM_DATA")) {
    let obj = JSON.parse(sessionStorage.getItem("YA_FORM_DATA"));
    Object.keys(obj).forEach((item) => {
      serchformData.value[item] = obj[item];
    });
  }
  let _data = JSON.parse(JSON.stringify(serchformData.value));
  if (_data.findTime) {
    _data.modifiedTimeStart = _data.findTime[0];
    _data.modifiedTimeEnd = _data.findTime[1];
    delete _data.findTime;
  }
  if (_data.assetTypeSet) {
    _data.assetTypeSet = _data.assetTypeSet.toString();
  }
  if (_data.deptIdSet) {
    _data.deptIdSet = _data.deptIdSet.toString();
  }
  queryHostAssets(_data).then((res) => {
    const { code, data = {} } = res;
    if (code == 200) {
      data.records.forEach((item) => {
        item.gatherType = "";
        item.gatherTypeNameSet.forEach((child) => {
          item.gatherType += child + "/";
        });
        item.gatherType = item.gatherType.substring(
          0,
          item.gatherType.length - 1
        );
      });
      tableData.value = data.records || [];
      total.value = data.total;
    }
  });
};
// 排序事件
const handleSortChange = (data) => {
  serchformData.value.column = "ip";
  serchformData.value.asc = data.asc;
  initData("init");
};
//页面挂载
onMounted(() => {
  permissionsButtons.map((item) => {
    bottomData.set(item.menuId, item);
  });
  // 操作处宽度的自适应
  column.length = bottomData.has(20005) ? column.length : column.length - 1;
  initData(); // 获取列表数据
  getButton();
  initDict();
  getDepteEvent();
});
//获取所属部门下拉框数据
const getDepteEvent = () => {
  getDeptData().then((res) => {
    const { data = {} } = res;
    data?.forEach((item) => {
      let obj = ref({});
      obj.value.label = item.deptName;
      obj.value.value = item.id;
      deptIdArr.value.push(obj.value);
    });
  });
};
// 重置按钮的事件
const reset = () => {
  initData("init");
};

//选中的行的信息
const handleSelectionChange = function (val) {
  selectData.value = val;
};
// 页面按钮事件执行
const tableBtnClick = (btn, row) => {
  btn.eventName(row);
};
/**
 * 弹窗
 */
//弹窗的数据
let dialogForm = ref();
//弹窗是否显示
let dialogProps = reactive({
  showDialog: false,
  title: "",
  size: "",
});
//填入的弹窗数据
const formData: any = ref({});
//批量与全部导出
const exportType = ref(false);
//弹框的表单数据
const formColumns = ref([
  {
    key: "fileType",
    type: "select",
    label: "选择格式",
    col: 24,
    options: fileTypeArr,
  },
]);
//弹窗的表单数据规则
const rules = ref({
  fileType: [
    {
      required: true,
      message: "请选择文件格式",
      trigger: "blur",
    },
  ],
});

//清空表单数据
let handleDialogOpen = () => {
  nextTick(() => {
    dialogForm.value.resetForm();
  });
};

//弹窗点击确定的表单校验
const handleConfirm = function () {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};
//批量导出
let getButton = () => {
  if (bottomData.has(200011)) {
    leftButtons.value.push({
      custom: "dropdown",
      title: bottomData.get(200011).label,
      customData: [
        {
          name: "批量" + bottomData.get(200011).label,
          eventName: function () {
            batchExport("part");
          },
        },
        {
          name: "全部" + bottomData.get(200011).label,
          eventName: function () {
            batchExport("all");
          },
        },
      ],
    });
  }
};
// 导出事件
const batchExport = function (type) {
  if (tableData.value && tableData.value.length != 0) {
    if (type == "part") {
      if (selectData.value && selectData.value.length == 0) {
        yaMessage("请选择要批量导出的数据", "warning");
        return;
      } else {
        exportType.value = true;
        formData.value.fileType = "";
        dialogProps.showDialog = true;
      }
    } else {
      exportType.value = false;
      formData.value.fileType = "";
      dialogProps.showDialog = true;
    }
  }
};
//批量导出的接口
const exportEvent = function () {
  let params: any = {};
  let selectedList = [];
  selectedList = selectData.value && selectData.value.map((item) => item.code);
  params.codeSet = selectedList;
  params.fileType = formData.value.fileType;
  params.fileName = "主机资产";
  batchExp(params).then((res) => {
    downLoadFile(res, "主机资产", formData.value.fileType);
    yaMessage("导出成功", "success");
    clearSelect();
  });
};
//全部导出接口
const exportAll = function () {
  let params: any = {};
  params.request = JSON.parse(JSON.stringify(serchformData.value));
  if (params.request.findTime) {
    params.request.modifiedTimeStart = params.request.findTime[0];
    params.request.modifiedTimeEnd = params.request.findTime[1];
    delete params.request.findTime;
  }
  params.fileType = formData.value.fileType;
  params.fileName = "主机资产";
  addDataExp(params).then((res) => {
    downLoadFile(res, "主机资产", formData.value.fileType);
    yaMessage("导出成功", "success");
    clearSelect();
  });
};
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// 清空选择的值
const clearSelect = () => {
  multipleTableRef.value.$refs["ya-table"].$refs["ya-table"].$refs[
    "ya-table"
  ].clearSelection();
};
//弹窗的确定事件
const handleDialogEvent = function (data) {
  if (data.eventName == "successSubmit") {
    if (exportType.value) {
      exportEvent();
    } else {
      exportAll();
    }
    dialogProps.showDialog = false;
  }
};
//一共多少条数据
const total = ref(0);
//每页显示多少条的变化事件
const sizeChange = function (val: number) {
  serchformData.value.pageSize = val;
  initData("page");
};
//页码改变的事件
const currentChange = function (val: number) {
  serchformData.value.pageIndex = val;
  initData("page");
};
//去应用页面
const goToApplication = function (val) {
  localStorage.setItem("YA_HOST_ASSET_DATA", JSON.stringify(val));
  router.push({
    path: "./hostAssets/yappl",
  });
};
//去详情页面
const goToDetail = function (val) {
  localStorage.setItem("YA_HOST_ASSET_DATA", JSON.stringify(val));
  router.push({
    path: "./hostAssets/adetail",
  });
};
</script>
<style lang="scss" scoped>
.ya-ipv {
  color: #0095ff;
  cursor: pointer;
}
img {
  width: 18px;
  height: 18px;
  vertical-align: middle;
}
.ya-img {
  margin-right: 8px;
}
.ya-tag {
  display: flex;
  height: 100%;
  align-items: center;
  border: none;
  background-color: transparent;
}
.ya-tag1,
.ya-tag2,
.ya-tag3,
.ya-num {
  border-radius: 2px;
  line-height: 24px;
  padding: 2px 8px;
}
.ya-tag1 {
  background: rgba(#3cd597, 0.1);
  color: #3cd597;
  margin-right: 12px;
}
.ya-tag2 {
  background: #fdf6ec;
  color: #da8302;
  margin-right: 12px;
}
.ya-tag3 {
  background: #ecf5ff;
  color: #0079eb;
  margin-right: 12px;
}
.ya-num {
  background: rgba(0, 149, 255, 0.12);
  color: #0095ff;
}
.ya-alive {
  color: #55cd79;
}
.ya-offline {
  color: #afafaf;
}
.ya-abnormal {
  color: #f99c6a;
}
.ya-cursor {
  cursor: pointer;
}
.ya-status {
  display: flex;
  align-items: center;
}
</style>
